<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <a-button type="default" @click="handleExport()">
          <Icon icon="i-ant-design:download-outlined" /> {{ t('导出') }}
        </a-button>
        <a-button type="default" @click="handleImport()">
          <Icon icon="i-ant-design:upload-outlined" /> {{ t('导入') }}
        </a-button>

        <!-- <a-button type="default" @click="handleSyn({})" v-auth="'rd:rd10:rdrecord10:edit'">
          <Icon icon="i-simple-line-icons:refresh" /> {{ t('同步任务') }}
        </a-button> -->
        <Popconfirm placement="bottom" :title="t('确认同步任务吗?')" @confirm="handleSyn({})">
          <a-button type="default" v-auth="'rd:rd10:rdrecord10:edit'">
            <Icon icon="i-simple-line-icons:refresh" /> {{ t('同步任务') }}
          </a-button>
        </Popconfirm>
        <!-- <a-button type="default" @click="handleCancleTask({})" v-auth="'rd:rd10:rdrecord10:edit'">
          <Icon icon="ant-design:save-outlined" /> {{ t('退料撤销') }}
        </a-button> -->
        <Popconfirm placement="bottom" :title="t('是否撤销？')" @confirm="handleCancleTask({})">
          <a-button type="default" v-auth="'rd:rd10:rdrecord10:edit'">
            <Icon icon="ant-design:save-outlined" /> {{ t('退料撤销') }}
          </a-button>
        </Popconfirm>
        <a-button type="default" @click="handleShdPrint()" >
          <Icon icon="ant-design:printer-twotone" /> {{ t('打印') }}
        </a-button>
        <!-- <a-button type="default" @click="handleGenerateTask({})" v-auth="'rd:rd10:rdrecord10:edit'">
          <Icon icon="ant-design:save-outlined" /> {{ t('生成下架任务') }}
        </a-button> -->
        <Popconfirm placement="bottom" :title="t('是否生成下架任务？')" @confirm="handleGenerateTask({})">
          <a-button type="default" v-auth="'rd:rd10:rdrecord10:edit'">
            <Icon icon="ant-design:save-outlined" /> {{ t('生成下架任务') }}
          </a-button>
        </Popconfirm>
        <a-button type="success" ghost @click="handleForm1({})" v-auth="'rd:rd10:rdrecord10:edit'">
          <Icon icon="i-fluent:add-12-filled" /> {{ t('新增') }}
        </a-button>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ id: record.id,sourceFlag: record.sourceFlag,rkStatus: record.rkStatus })">
          {{ record.fbillno }}
        </a>
      </template>
    </BasicTable>
    
    <InputRKForm @register="registerRkDrawer" @success="handleSuccess" />
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <InputView @register="registerViewDrawer" @success="handleSuccess" />
    <BasicModal v-bind="$attrs" @register="registerModal" title="请确认拣货方式" @ok="handleQr">
      <BasicForm @register="registerForm" />
    </BasicModal>

    <FormImport @register="registerImportModal" @success="handleSuccess" />
    <PrintModal @register="registerPrintModal" />
  </div>
</template>
<script lang="ts" setup name="ViewsWmsRdRd10Rdrecord10TlList"> 
  import { unref,onMounted, defineProps } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import {
    rdrecord10Delete,
    rdrecord10ListData,
    rdrecord10Syn,
    harvestRevoke,
    synMaterialReturn,
    materialRevoke,
    generateTask,
  } from '/@/api/wms/rd/rd10/rdrecord10';
  import { useDrawer } from '/@/components/Drawer';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { FormProps, BasicForm, useForm } from '/@/components/Form';
  import InputForm from './form.vue';
  import InputRKForm from '/@/views/wms/wh/rd01/rd01/form.vue';
  import InputView from './formView.vue';
  import FormImport from './formImport.vue';
  import { companyTreeData } from '/@/api/sys/company';
  import { useUserStore } from '/@/store/modules/user';
  import { propTypes } from '/@/utils/propTypes';
  import PrintModal from '/@/components/print/printModal.vue';
  import { Popconfirm } from 'ant-design-vue';
  const userStore = useUserStore();

  const { t } = useI18n('rd.rd10.rdrecord10');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);

  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: meta.title || t('入库任务单管理'),
  };

  const props = defineProps({
    bred: propTypes.string,
  });

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('公司'),
        field: 'companyCode',
        fieldLabel: 'companyName',
        component: 'TreeSelect',
        componentProps: {
          api: companyTreeData,
          allowClear: true,
          immediate: true,
          onChange: handleSuccess,
        },
      },
      {
        label: t('单据编号'),
        field: 'fbillno',
        component: 'Input',
      },
      {
        label: t('单据日期'),
        field: 'fdate',
        component: 'DatePicker',
        componentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          // showTime: { format: 'HH:mm' },
          showTime: false,
        }
      },
      // {
      //   label: t('供应商内码'),
      //   field: 'fsupplyid',
      //   component: 'Input',
      // },
      {
        label: t('供应商名称'),
        field: 'fsuppliername',
        component: 'Input',
      },
      {
        label: t('创建时间'),
        field: 'createDate',
        // component: 'DatePicker',
        component: 'RangePicker',
      },
      {
        label: t('备注'),
        field: 'fexplanation',
        component: 'Input',
      },
       {
        label: t('数据来源'),
        field: 'sourceFlag',
        component: 'Select',
        componentProps: {
          dictType: 'bas_source_type',
          allowClear: true,
        },
      },
       {
        label: t('状态'),
        field: 'rkStatus',
        component: 'Select',
        componentProps: {
          dictType: 'wms_rd10_status',
          allowClear: true,
        },
      },
      // {
      //   label: t('状态'),
      //   field: 'status',
      //   component: 'Select',
      //   componentProps: {
      //     dictType: 'sys_search_status',
      //     allowClear: true,
      //     onChange: handleSuccess,
      //   },
      // },
      // {
      //   label: t('备注信息'),
      //   field: 'remarks',
      //   component: 'Input',
      // },
    ],
    fieldMapToTime: [['createDate', ['createDate_gte', 'createDate_lte']]],

  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('公司'),
      dataIndex: 'companyName',
      key: 'a.company_name',
      sorter: true,
      width: 160,
      align: 'left',
    },
    {
      title: t('红蓝标志'),
      dataIndex: 'bred',
      key: 'a.bred',
      sorter: true,
      width: 90,
      align: 'center',
      dictType: 'wms_bred_status',
      // fixed: 'right',
    },
    {
      title: t('单据编号'),
      dataIndex: 'fbillno',
      key: 'a.fbillno',
      sorter: true,
      width: 110,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('状态'),
      dataIndex: 'rkStatus',
      key: 'a.rk_status',
      sorter: true,
      width: 100,
      align: 'center',
      dictType: 'wms_rd10_status',
      // fixed: 'right',
    },
    {
      title: t('单据日期'),
      dataIndex: 'fdate',
      key: 'a.fdate',
      sorter: true,
      width: 90,
      align: 'left',
    },
    // {
    //   title: t('供应商内码'),
    //   dataIndex: 'fsupplyid',
    //   key: 'a.fsupplyid',
    //   sorter: true,
    //   width: 130,
    //   align: 'left',
    // },
   
    {
      title: t('供应商编码'),
      dataIndex: 'fsupplierno',
      key: 'a.fsupplierno',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('供应商名称'),
      dataIndex: 'fsuppliername',
      key: 'a.fsuppliername',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('创建人'),
      dataIndex: 'createBy',
      key: 'a.create_by',
      sorter: true,
      width: 90,
      align: 'left',
    },
    {
      title: t('创建时间'),
      dataIndex: 'createDate',
      key: 'a.create_date',
      sorter: true,
      width: 120,
      align: 'left',
    },
    {
      title: t('备注'),
      dataIndex: 'fexplanation',
      key: 'a.fexplanation',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('数据来源'),
      dataIndex: 'sourceFlag',
      key: 'a.source_flag',
      sorter: true,
      width: 90,
      align: 'center',
      dictType: 'bas_source_type',
      // fixed: 'right',
    },
    // {
    //   title: t('修改时间'),
    //   dataIndex: 'updateDate',
    //   key: 'a.update_date',
    //   sorter: true,
    //   width: 130,
    //   align: 'center',
    // },
    // {
    //   title: t('备注信息'),
    //   dataIndex: 'remarks',
    //   key: 'a.remarks',
    //   sorter: true,
    //   width: 130,
    //   align: 'left',
    // },
  ];

  const actionColumn: BasicColumn = {
    width: 60,
    actions: (record: Recordable) => [
      {
        icon: 'i-ant-design:delete-outlined',
        color: 'error',
        title: t('删除入库任务单'),
        popConfirm: {
          title: t('是否确认删除入库任务单'),
          confirm: handleDelete.bind(this, record),
        },
        auth: 'rd:rd10:rdrecord10:edit',
        ifShow: () => {
          return record.sourceFlag !== '0' && record.rkStatus == '0';
        },
      },
    ],
  };

  const [registerRkDrawer, { openDrawer: openRkDrawer }] = useDrawer();
  const [registerViewDrawer, { openDrawer: openViewDrawer }] = useDrawer();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, getForm, setProps, getSelectRows, getSelectRowKeys }] = useTable({
    api: rdrecord10ListData,
    beforeFetch: (params) => {
      params.bred = 0;
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    immediate: false,
    rowSelection: {
      type: 'checkbox',
    },
  });

  function handleRkForm(record: Recordable) {
    openRkDrawer(true, record);
  }
  
  function handleForm1(record: Recordable) {
    record.bred = 0;
    openDrawer(true, record);
  }

  function handleForm(record: Recordable) {
    if(record.sourceFlag == '1' && record.rkStatus == '0'){
      openDrawer(true, record);
    }else{
      openViewDrawer(true, record);
    }
    // if(record.sourceFlag == '0'){
    //   openViewDrawer(true, record);
    // }else{
    //   openDrawer(true, record);
    // }
  }

  async function handleExport() {
    const { ctxAdminPath } = useGlobSetting();
    downloadByUrl({
      url: ctxAdminPath + '/rd/rd10/rdrecord10/exportData',
      params: {
        bred: 0,
        ...getForm().getFieldsValue(),
      },
    });
  }

  const [registerImportModal, { openModal: importModal }] = useModal();

  function handleImport() {
    importModal(true, {});
  }

  async function handleDelete(record: Recordable) {
    const params = { id: record.id };
    const res = await rdrecord10Delete(params);
    showMessage(res.message);
    handleSuccess(record);
  }

  // 同步K3到货单信息
  async function handleSyn() {
    const res = await synMaterialReturn({});
    showMessage(res.message);
    handleSuccess({});
  }
  async function handleCancleTaskSh() {
    let arr = await getSelectRows();
    if (getSelectRows().length == 0) {
      showMessage(t('请先选择一行数据'));
      return;
    } else if (getSelectRows().length > 1) {
      showMessage(t('只能选择一行数据'));
      return;
    }
    // ids: getSelectRowKeys().join(','),
    const data = await harvestRevoke({ id: arr[0].id });
    showMessage(data.message);
    handleSuccess({});
  }

  async function handleCancleTask() {
    let arr = await getSelectRows();
    if (getSelectRows().length == 0) {
      showMessage(t('请先选择一行数据'));
      return;
    } else if (getSelectRows().length > 1) {
      showMessage(t('只能选择一行数据'));
      return;
    }
    // ids: getSelectRowKeys().join(','),
    const data = await materialRevoke({ id: arr[0].id });
    showMessage(data.message);
    handleSuccess({});
  }
  const [registerForm, { validate }] = useForm({
    labelWidth: 100,
    schemas: [
      {
        label: t('拣货方式'),
        field: 'type',
        component: 'Select',
        defaultValue: '1',
        componentProps: {
          dictType: 'jh_type',
          // allowClear: true,
        },
        required: true,
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });
  const [registerModal, { openModal, closeModal, setModalProps }] = useModal();
  async function handleGenerateTask() {
    // if (getSelectRows().length) {
    //   let selIds = getSelectRows().map((item) => item.id).join(',')
    //   const res = await generateTask({ selIds: selIds, type: '4' });
    //   showMessage(res.message);
    //   handleSuccess({});
    // } else {
    //   showMessage('请先选择数据');
    // }
    let arr = await getSelectRows();
    if (getSelectRows().length == 0) {
      showMessage(t('请先选择一行数据'));
      return;
    }
    openModal(true, {});
  }
  async function handleQr() {
    try {
      let dataValidate = await validate();
      setModalProps({ confirmLoading: true });
      const jhPlanAreaList = getSelectRows();
      const ids = jhPlanAreaList.map((item) => item.id).join(',');
      const data: any = {
        ...dataValidate,
        selIds: ids,
      };
      const res = await generateTask(data);
      showMessage(res.message);
      reload();
      closeModal();
      // setTableData3([]);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleSuccess(record: Recordable) {
    reload({ record });
  }

  onMounted(async () => {
    setProps();
    handleCompany();
    getHomePage();
    console.log(router.currentRoute.value.query,'-------')
  });

  async function handleCompany() {
    await getForm().setFieldsValue({
      companyCode: userStore.getProjecte.code,
    });
    reload();
    await getForm().setFieldsValue({
      companyCode: userStore.getProjecte.code,
    });
  }

  async function getHomePage() {
    if(router.currentRoute.value.query.homePage == 'true'){
      await getForm().setFieldsValue({
        rkStatus: '0',
      });
      reload();
    }
  }

  const [registerPrintModal, { openModal: openPrintModal }] = useModal();
  async function handleShdPrint() {
    let arr = await getSelectRowKeys();
    if (getSelectRowKeys().length == 0) {
      showMessage(t('请先选择数据'));
      return;
    }
    const ids = getSelectRowKeys().join(',');
    console.log(ids);
    let params = {
      ids: ids,
      title: '入库退料单',
      height: '0.9',
      width: '0.9',
      fileName: '入库退料单',
    };
    openPrintModal(true, params);
  }
</script>
